package com.oc.mba.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.oc.mba.dao.BaseDAOHibernate;
import com.oc.mba.dao.MessageDAO;
import com.oc.mba.entity.MessageEntity;
import com.oc.mba.util.CommLog;

@Repository
public class MessageDAOImpl extends BaseDAOHibernate implements MessageDAO{
	
	private static final CommLog logger = new CommLog(MessageDAOImpl.class);
	
	public List<MessageEntity> findByProperty(String propertyName, Object value) {
		logger.debug("finding MessageEntity instance with property: " + propertyName + ", value: " + value);
		try {
			String hsql = "from MessageEntity as model where model." + propertyName + "= ? order by model.id";
			return getHibernateTemplate().find(hsql, value);
		} catch (RuntimeException re) {
			logger.error("find by property name failed", re);
			throw re;
		}
	}
	
	@Override
	public void save(MessageEntity messageEntity) {
		logger.debug("save MessageEntity : " + messageEntity);
		try {
			getHibernateTemplate().save(messageEntity);
			logger.debug("save message success.");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("save MessageEntity failed.", e);
		}
	}

	@Override
	public void delete(Integer messageID) {
		logger.debug("delete MessageEntity. messageID=" + messageID);
		try {
			MessageEntity message = findMessage(messageID);
			if (message != null) {
				getHibernateTemplate().delete(message);
				logger.debug("delete message success.");
			}
			else {
				logger.debug("message doesn't exist.");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("save MessageEntity failed.", e);
		}
	}

	@Override
	public MessageEntity findMessage(Integer messageID) {
		logger.debug("find MessageEntity. messageID=" + messageID);
		MessageEntity messageEntity = null;
		try {
			messageEntity = getHibernateTemplate().load(MessageEntity.class, messageID);
			if (messageEntity != null) {
				logger.debug("find message success. message exist.");
				return messageEntity;
			}
			else {
				logger.debug("find message success. message doesn't exist.");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("find MessageEntity failed.", e);
		}
		return messageEntity;
	}

	@Override
	public List<MessageEntity> finAllMessage() {
		logger.debug("finding all MessageEntity");
		try {
			String hsql = "from MessageEntity as model";
			return getHibernateTemplate().find(hsql, null);
		} catch (RuntimeException re) {
			logger.error("find all MessageEntity failed", re);
			throw re;
		}
	}

}
